﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using BUS;
using System.Drawing.Imaging;
namespace GPBenhLanh
{
    public partial class frmChupHinh : DevExpress.XtraEditors.XtraForm
    {
        public frmChupHinh()
        {
            InitializeComponent();
        }
        public frmChupHinh(string _sotieuban, int _isCl)
        {
            InitializeComponent();
            sotieuban = _sotieuban;
           
            isCl = _isCl;
        }
        private string pathTemp = "";
        public string sThuMucLuu = "";
        public string sThuGoc = "";
        private Bitmap bmHinh1 = null;
        private Bitmap bmHinh2 = null;
        public string sotieuban = "";
        public string DVuCode = "";
        public string sophieu = "";
        public int isCl = 0;
        private int flag = 0;
        private int[] isImg = new int[4]{0,0,0,0} ;
        public delegate void DelegeChupH(object sender, Object data);
        public event DelegeChupH thoatEven;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="urlTemp">url tren may local</param>
        /// <param name="urlSer">url tren may server</param>
        public void ReloadImage(string urlTemp, string urlSer)
        {
            //load hinh x100
            string urlLocal1 = "";
            string urlServ1 = "";
            string[] words = txtsobn.Text.Split(new string[] { "*" }, StringSplitOptions.None);
            string sobn = "";
            
                if (words.Length > 1)
                    sobn = words[0] + "_" + words[1];                   
                else
                    sobn = txtsobn.Text;
            DataTable dtPL = GetThongTinSearchBUS.SearchPhanLoaiDV(DVuCode);
            int NhomPL = 0;
            if (dtPL.Rows.Count > 0)
                NhomPL = int.Parse(dtPL.Rows[0]["IDLoai"].ToString());
            //if (DVuCode == "GE56" && isCl == 1)
            if (NhomPL == 1 && isCl == 1)
            {
                urlLocal1 = urlTemp + "x100_" + txtSoTieuBan.Text + "_" + isCl.ToString() + ".jpg";
                urlServ1 = urlSer +  "x100_" + txtSoTieuBan.Text + "_" + isCl.ToString() + ".jpg";
            }
            else
            {
                urlLocal1 = urlTemp + "x100_" + txtSoTieuBan.Text + ".jpg";
                urlServ1 = urlSer +  "x100_" + txtSoTieuBan.Text + ".jpg";
            }             
            
            if (File.Exists(urlLocal1))
            {
                LoadHinh(pic100, urlLocal1);
            }
            else if (File.Exists(urlServ1))
            {
                LoadHinh(pic100, urlServ1);
            }
            else
            {
                ClearHinh(1);
                if (pic100.Name == "pic100")
                {
                    bmHinh1 = null;
                    pic100.Image = null;
                }
            }
            
            //load hinh x400
            string urlLocal2 = "";
             string urlServ2 = "";
             
            //if (DVuCode == "GE56" && isCl == 1)
            if (NhomPL == 1 && isCl == 1)
            {
                urlLocal2 = urlTemp + "\\x400_" + txtSoTieuBan.Text + "_" + isCl.ToString() + ".jpg";
                urlServ2 = urlSer +  "\\x400_" + txtSoTieuBan.Text + "_" + isCl.ToString() + ".jpg";
            }
            else
            {
                urlLocal2 = urlTemp + "x400_" + txtSoTieuBan.Text + ".jpg";
                urlServ2 = urlSer + "\\x400_" + txtSoTieuBan.Text + ".jpg";
            } 
            if (File.Exists(urlLocal2))//neu co hinh o local thi load o local 
            {
                LoadHinh(pic400, urlLocal2);
            }
            else if (File.Exists(urlServ2))//neu co hinh o server thi load o local
            {               
                LoadHinh(pic400, urlServ2);
            }
            else
            {
                ClearHinh(2);
                if (pic400.Name == "pic400")
                {
                    bmHinh2 = null;
                    pic400.Image = null;
                }
            }
        }

        private void frmChupHinh_Load(object sender, EventArgs e)
        {
            try
            {
                
                //load lai hinh neu da chup roi                
                txtsohs.Text = "";
                txtsobn.Text = "";
                txtSoTieuBan.Text = sotieuban;
               
                txtdiachi.Text = "";
                txtGioi.Text = "";
                txtHoTen.Text = "";
                txttendv.Text = "";
                txtTuoi.Text = "";

                pathTemp = Application.StartupPath + "\\PictureTemp"  ;
                sThuGoc = sThuMucLuu+"\\" ;
                if (!Directory.Exists(pathTemp))
                {
                    Directory.CreateDirectory(pathTemp);
                }
                if (isCl == 1)
                {
                    txtSoTieuBan.Enabled = false;
                    btnNext.Visible = false;
                    btnPrevious.Visible = false;
                    btngo.Visible = false;
                    btngo_Click(sender, e);
                }
                else
                {
                    txtSoTieuBan.Enabled = true;
                }                
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH"+ex.Message.ToString(), "Thông Báo");
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {               
                ClearHinh(0);
                if (isCl == 1)
                {
                    if (thoatEven != null)
                    {
                        thoatEven(this, isImg);
                    }
                }
                this.Close();                
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH-" + ex.Message.ToString(), "Thông Báo");
            }
        }

        /// <summary>
        /// clear hinh tren picbox
        /// </summary>
        /// <param name="NumHinh">1: hinh 1; 2: hinh; 0: all</param>
        private void ClearHinh(int NumHinh)
        {
            if (NumHinh == 1)
            {
                if (bmHinh1 != null)
                {
                    bmHinh1.Dispose();
                    bmHinh1 = null;
                    pic100.Image = null;
                    pic100.Refresh();
                }
            }
            else if (NumHinh == 2)
            {
                if (bmHinh2 != null)
                {
                    bmHinh2.Dispose();
                    bmHinh2 = null;
                    pic400.Image = null;
                    pic400.Refresh();
                }
            }
            else if (NumHinh == 0)
            {
                if (bmHinh1 != null)
                {
                    bmHinh1.Dispose();
                    bmHinh1 = null;
                    pic100.Image = null;
                    pic100.Refresh();
                }
                if (bmHinh2 != null)
                {
                    bmHinh2.Dispose();
                    bmHinh2 = null;
                    pic400.Image = null;
                    pic400.Refresh();
                }
            }
        }

        private void LuuImage(string preName)
        {
            //ClearHinh(1);
            string[] words = txtsobn.Text.Split(new string[] { "*" }, StringSplitOptions.None);
            string sobn ="";           
            if (words.Length > 1)
                sobn = words[0] + "_" + words[1];               
            else
                sobn = txtsobn.Text;

            string ThuMucLuu = sThuMucLuu ;
            string pathHinhx1 = "";
            string pathHinh1Ser = "";
            DataTable dtPL = GetThongTinSearchBUS.SearchPhanLoaiDV(DVuCode);
            int NhomPL = 0;
            if (dtPL.Rows.Count > 0)
                NhomPL = int.Parse(dtPL.Rows[0]["IDLoai"].ToString());
           
            if (NhomPL == 1 && isCl == 1)
            {
                pathHinhx1 = pathTemp + preName + sotieuban + "_" + isCl.ToString() + ".jpg";
                pathHinh1Ser = ThuMucLuu + preName + sotieuban + "_" + isCl.ToString() + ".jpg";
            }
            else
            {
                pathHinhx1 = pathTemp + preName + sotieuban + ".jpg";
                pathHinh1Ser = ThuMucLuu + preName + sotieuban + ".jpg";
            }

            if (File.Exists(pathHinhx1))
            {
                flag = 1;
                isImg[0] = 1;
                if (!Directory.Exists(ThuMucLuu))
                {
                    Directory.CreateDirectory(ThuMucLuu);
                }
                              
                if (File.Exists(pathHinh1Ser))
                {
                    File.Delete(pathHinh1Ser);
                }
                //copy hinh to server
                File.Copy(pathHinhx1, pathHinh1Ser);
                //File.Delete(pathHinhx1);
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                ClearHinh(1);
                LuuImage(  "\\x100_");
                ClearHinh(2);
                LuuImage( "\\x400_");               
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH-" + ex.Message.ToString(), "Thông Báo");
                return;
            }
            finally
            {             
                flag = 1;
                if (thoatEven != null)
                {
                    thoatEven(this, isImg);
                }
            }
        }

        private void xoaHinh(string path, PictureBox edit)
        {           
            if (File.Exists(path))
            {
                if (edit.Name == "pic100")
                {
                   
                    if (bmHinh1 != null)
                    {                       
                        bmHinh1.Dispose();
                        pic100.Image = null;
                    }
                    File.Delete(path);
                }
                if (edit.Name == "pic400")
                {                   
                    if (bmHinh2 != null)
                    {
                        bmHinh2.Dispose();
                        pic400.Image = null;
                    }
                    File.Delete(path);
                }   
                
            }           
        }

        private void LoadHinh(PictureBox edit, string pathStr)
        {
            if (File.Exists(pathStr))
            {
                if (edit.Name == "pic100")
                {
                    Stream stream = File.Open(pathStr, FileMode.Open,
                    FileAccess.Read, FileShare.Delete);
                    bmHinh1 = (Bitmap)Bitmap.FromStream(stream);
                    stream.Close();
                    edit.Image = bmHinh1;
                }

                if (edit.Name == "pic400")
                {
                    Stream stream = File.Open(pathStr, FileMode.Open,
                    FileAccess.Read, FileShare.Delete);
                    bmHinh2 = (Bitmap)Bitmap.FromStream(stream);
                    stream.Close();                 
                    edit.Image = bmHinh2;
                }
            }
            
        }
        /// <summary>
        /// crop image to new size
        /// </summary>
        /// <param name="img">bitmap to crop</param>
        /// <param name="cropArea"> rectangle crop</param>
        /// <returns></returns>
        private static Image cropImage(Bitmap img, Rectangle cropArea)
        {
            Bitmap bmpImage = new Bitmap(img);
            return bmpImage.Clone(cropArea, bmpImage.PixelFormat);
        }

        /// <summary>
        ///  han chinh do sang cua anh
        /// </summary>
        /// <param name="pathStrbf">url hinh chua sua</param>
        /// <param name="pathStr">url hinh ket qua</param>
        private void ChinhDoSang(string pathStrbf,string pathStr)
        {
            Bitmap m_Bitmap;
            float value = int.Parse(txtdosang.Text) * 10;
            //doc file
            Stream stream = File.Open(pathStrbf, FileMode.Open,
                FileAccess.ReadWrite, FileShare.Delete);
            m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
            stream.Close();

            BitmapFilter.Brightness(m_Bitmap, value);//tang do sang 
            BitmapFilter.Contrast(m_Bitmap, (sbyte)value);//tang do net

            ///crop image
            Rectangle cropRect = new Rectangle(8, 3, m_Bitmap.Width - 22, m_Bitmap.Height - 4);
            Bitmap target = new Bitmap(m_Bitmap);
            target = (Bitmap)cropImage(m_Bitmap, cropRect);

            target.Save(pathStr, ImageFormat.Jpeg);//save file moi chup thanh file moi 
            File.Delete(pathStrbf);//xoa file goc di
        }

        private void btnChupHinh_Click(object sender, EventArgs e)
        {            
            try
            {              
                string pathStr = "";
                string pathStrbF = "";//Hinh truoc chinh sua
                string fileName = "";
                
                fileName = txtSoTieuBan.Text;
                DataTable dtPL = GetThongTinSearchBUS.SearchPhanLoaiDV(DVuCode);
                int NhomPL = 0;
                if (dtPL.Rows.Count > 0)
                    NhomPL = int.Parse(dtPL.Rows[0]["IDLoai"].ToString());

                //if (DVuCode == "GE56" && isCl == 1)
                if (NhomPL == 1 && isCl == 1)
                {
                    pathStr = pathTemp + "\\x100_" + sotieuban + "_" + isCl.ToString() + ".jpg";
                    pathStrbF = pathTemp + "\\x100_" + sotieuban + "bf_" + isCl.ToString() + ".jpg";
                }
                else
                {
                    pathStr = pathTemp + "\\x100_" + sotieuban + ".jpg";
                    pathStrbF = pathTemp + "\\x100_" + sotieuban + "bf_" + ".jpg";
                }
                ClearHinh(1);
                xoaHinh(pathStr, pic100);
                if (File.Exists(pathStrbF))
                {
                    File.Delete(pathStrbF);//neu truoc do co ton tai file thi xoa
                }
                //pic100.Image.Save(pathStrbF, ImageFormat.Jpeg);
                //if (File.Exists(pathStrbF))//Lưu hình vào thư mục tạm
                if (axezVidCap1.SaveDIB(pathStrbF))
                {
                    ChinhDoSang(pathStrbF, pathStr);//chinh sua do sang cho file vua moi chup                                       
                    ClearHinh(1);
                    LuuImage("\\x100_");
                    LoadHinh(pic100, pathStr);
                }                
            }
            catch(Exception ex)
            {
                MessageBox.Show("CH" + ex.Message.ToString(), "Thông Báo");                
                return;
            }
        }

        private void btnChupHinhX400_Click(object sender, EventArgs e)
        {            
            try
            {
                string pathStr = "";
                string pathStrbF = "";//Hinh truoc chinh sua
                DataTable dtPL = GetThongTinSearchBUS.SearchPhanLoaiDV(DVuCode);
                int NhomPL = 0;
                if (dtPL.Rows.Count > 0)
                    NhomPL = int.Parse(dtPL.Rows[0]["IDLoai"].ToString());
              
                if (NhomPL == 1 && isCl == 1)
                {
                    pathStr = pathTemp + "\\x400_" + sotieuban + "_" + isCl.ToString() + ".jpg";
                    pathStrbF = pathTemp + "\\x400_" + sotieuban + "bf_" + isCl.ToString() + ".jpg";
                }
                else
                {
                    pathStr = pathTemp + "\\x400_" + sotieuban + ".jpg";
                    pathStrbF = pathTemp + "\\x400_" + sotieuban + "bf_" + ".jpg";
                }
                
                ClearHinh(2);
                xoaHinh(pathStr, pic400);
                if (File.Exists(pathStrbF))
                {
                    File.Delete(pathStrbF);//neu truoc do co ton tai file thi xoa
                }
                //axezVidCap1.Scale(new System.Drawing.SizeF(640, 480));
                if (axezVidCap1.SaveDIB(pathStrbF))//Lưu hình vào thư mục tạm 
                //pic400.Image.Save(pathStrbF, ImageFormat.Jpeg);
                //if (File.Exists(pathStrbF))
                {
                    ChinhDoSang(pathStrbF,pathStr);
                    ClearHinh(2);
                    LuuImage("\\x400_");
                    LoadHinh(pic400, pathStr);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("CH-" + ex.Message.ToString(), "Thông Báo");              
                return;
            }
        }

        private void frmChupHinh_FormClosing(object sender, FormClosingEventArgs e)
        {
            ClearHinh(0);
        }

        private void frmChupHinh_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {      
                if (e.KeyCode == Keys.F9)
                {
                    btnChupHinh_Click(sender, e);
                }
                else if (e.KeyCode == Keys.F10)
                {
                    btnChupHinhX400_Click(sender, e);
                }
                else if (e.KeyCode == Keys.F11)
                {
                    btnLuu_Click(sender, e);
                }
                else if (e.KeyCode == Keys.Escape)
                {
                    btnThoat_Click(sender, e);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH-" + ex.Message.ToString(), "Thông Báo");
            }
        }
        /// <summary>
        /// Lay chuoi tu phai sang theo leng truyen vao
        /// </summary>
        /// <param name="value">chuoi can cat</param>
        /// <param name="length">chieu dai can cat</param>
        /// <returns>chuoi can cat</returns>
        public string Right(string value, int length)
        {
            if (value == "")
                return "";
            else
                return value.Substring(value.Length - length);
        }

        /// <summary>
        /// hàm lấy chuỗi từ trái sang
        /// </summary>
        /// <param name="value">giá trị của chuỗi cần cắt</param>
        /// <param name="length">chiều dài cảu chuỗi con</param>
        /// <returns>cuỗi cần lấy</returns>
        public string Left(string value, int length)
        {
            if (value == "")
                return "";
            else
                return value.Substring(0, length);
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            int numCur = 0, numNext = 0;
            string pre = "";
            if (txtSoTieuBan.Text == "")
                return;
            numCur = int.Parse(Right(txtSoTieuBan.Text, hensu.LengTeBao));
            if (numCur >= 1)
                btnPrevious.Enabled = true;
            numNext = numCur + 1;
            if (isCl == 1)//dang chup hinh cho cat lanh
            {
                pre = Left(txtSoTieuBan.Text, 5);

                txtSoTieuBan.Text = pre + numNext.ToString("0000");
            }
            else// dang chup hinh cho gpb
            {
                pre = Left(txtSoTieuBan.Text, 4);
                txtSoTieuBan.Text = pre + numNext.ToString("00000");
            }
            btngo_Click(sender, e);
        }
        private void CreateDir(DateTime NgNhan)
        {
            string goc = sThuGoc;
            DateTime dt;
            if (!NgNhan.Equals(""))
                dt = NgNhan;
            else
                dt = DateTime.Today;
            string namthang = dt.Year.ToString() + Uit.it_String.Right("0" + dt.Month.ToString(), 2);
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4));
            }
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4));
            }
            this.sThuMucLuu = goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4)+"\\";
        }

        private void btngo_Click(object sender, EventArgs e)
        {
            string SoTieuBan = txtSoTieuBan.Text;
            if (SoTieuBan.Equals(""))
                return;
            
            DataTable dt = GetThongTinSearchBUS.SearchDaXacNhanBySoTB(SoTieuBan);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    btnChupHinh.Enabled = true;
                    btnChupHinhX400.Enabled = true;
                    btnLuu.Enabled = true;

                    DateTime NgayNhan = DateTime.Parse(dt.Rows[0]["ngaynhan"].ToString());
                    CreateDir(NgayNhan);

                    txtHoTen.Text = dt.Rows[0]["HoTen"].ToString();
                    txtTuoi.Text = dt.Rows[0]["namsinh"].ToString()
                                 + "(" + dt.Rows[0]["tuoi"].ToString() + " Tuổi)";
                    txtGioi.Text = dt.Rows[0]["gioi"].ToString();
                    txtdiachi.Text = dt.Rows[0]["DiaChi"].ToString();
                    txttendv.Text = dt.Rows[0]["tendvu"].ToString();
                    txtsohs.Text = dt.Rows[0]["SoHS"].ToString();
                    txtsobn.Text = dt.Rows[0]["SoBN"].ToString();
                    sotieuban = txtSoTieuBan.Text;
                                     
                    ReloadImage(pathTemp, sThuMucLuu);
                    //tao folder tam tren local de luu hinh
                    string[] words = txtsobn.Text.Split(new string[] { "*" }, StringSplitOptions.None); 
                     string stb = "";
                     if (words.Length > 1)                        
                         stb = words[0] + "_" + words[1];                        
                     else
                         stb = txtsobn.Text;
                     pathTemp = Application.StartupPath + "\\PictureTemp" ;
                   
                    if (!Directory.Exists(pathTemp))
                    {
                        Directory.CreateDirectory(pathTemp);
                    }
                }
                else
                {
                    txtHoTen.Text = "";
                    txtTuoi.Text = "";
                    txtGioi.Text = "";
                    txtdiachi.Text = "";
                    txttendv.Text = "";
                    txtsohs.Text = "";
                    txtsobn.Text = "";
                }
            }
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            int numCur = 0, numPrev = 0;
            string pre = "";
            if (txtSoTieuBan.Text == "")
                return;
            numCur = int.Parse(Right(txtSoTieuBan.Text, hensu.LengTeBao));
            if (numCur <= 2)
                btnPrevious.Enabled = false;
            numPrev = numCur - 1;
            if (isCl == 1)//dang chup hinh cho cat lanh
            {
                pre = Left(txtSoTieuBan.Text, 5);
                txtSoTieuBan.Text = pre + numPrev.ToString("0000");
            }
            else// dang chup hinh cho gpb
            {
                pre = Left(txtSoTieuBan.Text, 4);
                txtSoTieuBan.Text = pre + numPrev.ToString("00000");
            }
            btngo_Click(sender, e);
        }

        private void txtSoTieuBan_Validated(object sender, EventArgs e)
        {
            btngo_Click(sender, e);
        }

        private void txtSoTieuBan_Validating(object sender, CancelEventArgs e)
        {
            txtSoTieuBan.Text = txtSoTieuBan.Text.ToUpper();
        }

        private void pic100_Click(object sender, EventArgs e)
        {
            if(btnChupHinh.Enabled ==true)
                btnChupHinh_Click(sender, e);
        }

        private void pic400_Click(object sender, EventArgs e)
        {
            if(btnChupHinhX400.Enabled == true)
                btnChupHinhX400_Click(sender, e);
        }
    }
}